const userService = require("../service/user.service");
const { NAME_IS_ALREADY_EXISTS, NAME_OR_PASSWORD_IS_REQUIRED } = require("../config/error");

const md5password = require("../utils/md5password");

const verifyUser = async (ctx, next) => {
  const { name, password } = ctx.request.body;

  // 判断用户是否存在
  if (!name || !password) {
    ctx.app.emit("error", NAME_OR_PASSWORD_IS_REQUIRED, ctx);
    return;
  }
  // 判断name 是否在数据库中存在
  const users = await userService.findUser(name);

  if (users.length) {
    ctx.app.emit("error", NAME_IS_ALREADY_EXISTS, ctx);
    return;
  }
  // 执行在一个中间间
  await next();
};

// 处理密码 加密
const handlePassword = async (ctx, next) => {
  const { name, password } = ctx.request.body;

  // 对密码进行加密 在赋值给
  ctx.request.body.password = md5password(password);
  await next();
};

module.exports = {
  verifyUser,
  handlePassword,
};
